/**
 * Created by zhouli on 2019/2/25.
 */
import React from 'react';
import {connect} from 'react-redux';
import {Input, message, Button, Spin, Checkbox, Modal} from 'antd';
import LoginService from 'containers/login/login.service';
import {getUrlSearchParams, messages, getToken, trim} from 'share/common';
import "styles/login/components/company-login/company-login.scss";
import 'styles/login/login-refactoring-ui.scss'

class CompanyLogin extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      username: "",
      password: "",
      loginType: "",
      clientName: "",
      companyWayLoginStep: 1,
      readAgree: false,//阅读并同意
      visible: false,//汇联易协议
      verifyCodeIsPass: false,//手机与图片验证码是否通过
      header: "",
      title: "",
      protocol: "",
      tenantProtocol: false,
    }
  }

  componentDidMount() {
    this.props.onRef(this);
  }

  companyWayLoginStep1 = () => {
    this.setState({
      loading: false,
      companyWayLoginStep: 1
    })
  };
  //登录
  login = () => {
    let {username,password,loginType,clientName}=this.state;
    let publicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCDAxLcb5T5WrS1RfVCy6YcmE8Ue2y33mwWnE+K5y1B61eXx0wcS4yoNEWC/7Mmg405I5SVTWSxFjgkYE5Bmd2O2jiDV/TGPWIVQrn5L4lIypbCnb5isHI+udpT0jPyf4ixdzsAu8FWcDgL/DXBO6ieKQ0gdngg5Tce7Frcumi3HQIDAQAB';
    if (username.split("/").length > 1) {
      //截取账号
      username = username.split("/")[1];
    }
    let login = {
      username: encodeURIComponent(LoginService.encrypt(username, publicKey)),
      password: encodeURIComponent(LoginService.encrypt(password, publicKey)),
      loginType,
      clientName,
      loginId: undefined,
      cryptType: 3
    };
    this.props.login(login);
  };
  companyNextStep = () => {
    let {username} = this.state;
    let Request = new getUrlSearchParams(); //实例化
    if (trim(username) === "") {
      message.warning(messages('login.key26')/*请输入账号*/);
      return;
    }
    let redirect_url = window.location.href + "?loginType=sso";
    LoginService.loginDecideV2(username, redirect_url)
      .then((res) => {
        this.setState({
          header: res.data["x-helios-tenant"],
        }, () => {
          this.getTenantProtocol();
        });
        // 返回结果实例
        // {
        //     "loginUrl": "url",//直接跳转
        //     "loginType":"sso/ssoDirect",
        //     "clientName":"handdir"
        // }
        let loginType = res.data;
        if (loginType.message && loginType.message.length > 0) {
          message.warn(loginType.message);
        }
        if (loginType.code) {
          // 如果有错误，才有这个字段，否则没有这个字段
          // 详情见 bug 15533
          return;
        }
        //企业单点登录，客户端名称需要记住，点击退出的时候
        window.sessionStorage.setItem("sso_clientName", loginType.clientName);
        window.sessionStorage.setItem("sso_loginType", loginType.loginType);
        if (loginType.loginType === "sso" && loginType.loginUrl) {
          //关键是这种方式，需要直接跳转URL
          window.location.href = loginType.loginUrl;
        } else if (loginType.loginType === "ssoDirect") {
          if (loginType.clientName === "talefull") {
            //这又是另一种特殊的登录方式
            //截取url当做用户名，截取indate当做密码
            this.setState({
              username: Request.url,
              password: Request.indate,
              loginType: "ssoDirect",
              clientName: loginType.clientName
            }, () => {
              this.login()
            })
          } else {
            //单点直登录
            this.setState({
                loginType: "ssoDirect",
                clientName: loginType.clientName,
                companyWayLoginStep: 2,
              })
          }
        } else {
          //普通登录
          this.setState({
              loginType: "",
              clientName: "",
              companyWayLoginStep: 2,
            })
        }
      })
  };
  //输入时，取消loading
  inputUsernameHandler = (evt) => {
    this.setState({
      username: evt.target.value,
      loading: false
    });
  };
  //输入时，取消loading
  inputPasswordHandler = (evt) => {
    this.setState({
      password: evt.target.value,
      loading: false
    });
  };

  getTenantProtocol = () => {
    const {header} = this.state;
    LoginService.getTenantProtocol(header)
      .then(res => {
        if(res.data && res.data.i18n && res.data.i18n.title && res.data.i18n.title.length) {
          res.data.i18n.title.map(item => {
            if (item.language === this.props.language.code) {
              this.setState({
                title: item.value,
              });
            }
          });
        }
        if(res.data && res.data.i18n && res.data.i18n.content && res.data.i18n.content.length) {
          res.data.i18n.content.map(item => {
            if (item.language === this.props.language.code) {
              this.setState({
                protocol: item.value,
              });
            }
          });
        }
      })
      .catch(err => {

      })
  };

  readAgreeChange=(e)=>{
    this.setState({readAgree: e.target.checked})
  };

  clickProtocol = (e, bool) => {
    this.setState({
      visible: true,
      tenantProtocol: bool,
    })
  };

  //渲染企业登录：第一步
  renderCompanyWayLoginStep1 = () => {
    const {loading, username} = this.state;
    return (
      <div>
        <div className="inp-wrap">
          <Input
            className="company-login-tip-inp"
            size="large"
            placeholder={messages('login.key31')/*格式：代码/账号或者邮箱*/}
            onChange={this.inputUsernameHandler}
          />
        </div>

        <Button type="primary"
                size="large"
                className="login-refactoring-btn"
                disabled={!username}
                loading={loading}
                onClick={this.companyNextStep}> {messages('login.key3')/*下一步*/}
        </Button>
      </div>
    )
  };
  //渲染企业登录：第二步
  renderCompanyWayLoginStep2 = () => {
    const {loading, readAgree, visible, protocol, title, tenantProtocol} = this.state;
    let link = this.props.language.code.toLowerCase() === "zh_cn" ? "https://console.huilianyi.com/register/pages/protocol.html"
      : "https://console.huilianyi.com/register/pages/protocol-en.html";
    return (
      <div>
        <div className="inp-wrap">
          <Input
            size="large"
            type="password"
            placeholder={messages('login.key29')/*密码*/}
            onChange={this.inputPasswordHandler}
            onPressEnter={this.login}
          />
        </div>
        <div className="protocol-check-wrap">
          <div className="protocol-check-agree">
            &nbsp;
            <Checkbox checked={readAgree}
                      onChange={(e) => {this.readAgreeChange(e)}}/>
            &nbsp;
            <span style={{paddingLeft: 6}}>{messages('login.key57')/*阅读并同意*/}
              <span className="protocol-check-title"
                    onClick={(e) => {this.clickProtocol(e, false)}}>
                &nbsp;{messages('login.key11'/*汇联易用户使用协议*/)}
              </span>
              <span className="protocol-check-title"
                    style={{marginLeft: 10}}
                    onClick={(e) => {this.clickProtocol(e, true)}}>
                {title}
              </span>
            </span>
          </div>
        </div>
        <Button type="primary"
                size="large"
                className="login-refactoring-btn"
                onClick={this.login}
                disabled={!readAgree}
                loading={loading}> {messages('login.key30')/*登录*/}
        </Button>
        <Modal visible={visible}
               width={780}
               className={"protocol-modal"}
               onCancel={() => {this.setState({visible: false})}}
               footer={null}>
          {
            tenantProtocol ?
              <div dangerouslySetInnerHTML={{__html: protocol}} style={{margin: 30, maxHeight: 450, overflow: "auto"}}/>
            :
              <iframe src={link} width={730} height={450} style={{border: 'none', marginTop: 30}}/>
          }
        </Modal>
      </div>
    )
  };
  //渲染企业登录
  renderCompanyWayLogin = () => {
    const {companyWayLoginStep} = this.state;
    if (companyWayLoginStep === 1) {
      return (<div> {this.renderCompanyWayLoginStep1()}</div>)
    } else if (companyWayLoginStep === 2) {
      return (<div>{this.renderCompanyWayLoginStep2()}</div>)
    }
  };

  render() {
    return (
      <div className="company-login login-refactoring-ui">
        {this.renderCompanyWayLogin()}
      </div>
    )
  }
}

CompanyLogin.propTypes = {
  onFindPassword: React.PropTypes.func,//
};

CompanyLogin.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    tenant: state.login.tenant
  }
}

export default connect(mapStateToProps)(CompanyLogin);

